package com.pro.admin.web.guanwang;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.admin.annotation.RequiresPermissionsDesc;
import com.pro.core.util.ResponseUtil;
import com.pro.db.domain.GuopuCategory;
import com.pro.db.service.itf.IGuopuCategoryService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/category")
@Validated
public class GuopuCategoryController {
    private final Log logger = LogFactory.getLog(GuopuCategoryController.class);

    @Autowired
    private IGuopuCategoryService categoryService;

    /**
     * @apiDefine category 栏目接口
     *
     */


    /**
     * @api {POST} /admin/category/create 1.1 添加栏目
     * @apiName category create
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} name 栏目名称
     * @apiParam {String} level 栏目等级(L1:一级栏目，L2:二级栏目)
     * @apiParam {int} type 栏目类型(0标题，1富文本，2列表，3视频，4图片)
     * @apiParam {int} [pid] 父栏目id，二级类目需传
     * @apiParam {int} [pushStatus] 是否展示，默认1展示， 0不展示
     * @apiParam {int} [showHome] 是否展示内容到首页，默认0不展示， 1展示
     * @apiParam {int} [showApp] 是否展示内容到APP，默认0不展示， 1展示
     * @apiParam {String} [iconUrl] 栏目图标，如果是展示在APP端，需要传
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:create")
    @RequiresPermissionsDesc(menu={"栏目管理" , "栏目分类"}, button="添加")
    @PostMapping("/create")
    public Object create(@RequestBody GuopuCategory category) {
        Object error = validate(category);
        if (error != null) {
            return error;
        }

        GuopuCategory last = categoryService.getOne(new QueryWrapper<GuopuCategory>()
            .orderByDesc("push_sort"));
        if(null != last){
            category.setPushSort(last.getPushSort()+1);
        }else {
            category.setPushSort(1);
        }

        categoryService.save(category);
        return ResponseUtil.ok(category);
    }

    /**
     * @api {GET} /admin/category/list 1.2 栏目列表
     * @apiName category list
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} level 栏目等级(L1:一级栏目，L2:二级栏目)
     * @apiParam {int} [pid] 父栏目id，获取二级类目需传
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:list")
    @RequiresPermissionsDesc(menu={"栏目管理" , "栏目分类"}, button="查询")
    @GetMapping("/list")
    public Object list(Integer pid, @NotNull String level,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        Page<GuopuCategory> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<GuopuCategory> pList = categoryService.page(pageVo,
                new QueryWrapper<GuopuCategory>()
                        .eq(pid != null,"pid",pid)
                        .eq("level",level)
                        .orderByDesc("push_sort"));

        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());

        return ResponseUtil.ok(data);
    }

    private Object validate(GuopuCategory category) {
        String name = category.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument("栏目名称");
        }

        String level = category.getLevel();
        if (StringUtils.isEmpty(level)) {
            return ResponseUtil.badArgument("栏目等级");
        }
        if (!level.equals("L1") && !level.equals("L2")) {
            return ResponseUtil.badArgumentValue("栏目等级");
        }

        Integer pid = category.getPid();
        if (level.equals("L2") && (pid == null)) {
            return ResponseUtil.badArgument("二级栏目需指定一级栏目");
        }

        if(category.getShowApp().equals(1) && StringUtils.isEmpty(category.getIconUrl())){
            return ResponseUtil.fail("展示在APP端的栏目，需设置图标");
        }

        return null;
    }

    /**
     * @api {GET} /admin/category/read 1.3 栏目详情
     * @apiName category read
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 栏目id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:read")
    @RequiresPermissionsDesc(menu={"栏目管理" , "栏目分类"}, button="详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        GuopuCategory category = categoryService.getById(id);
        return ResponseUtil.ok(category);
    }

    /**
     * @api {Post} /admin/category/update 1.4 栏目编辑
     * @apiName category update
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 栏目id
     * @apiParam {String} [name] 栏目名称
     * @apiParam {String} [level] 栏目等级(L1:一级栏目，L2:二级栏目)
     * @apiParam {int} [pid] 父栏目id，二级类目需传
     * @apiParam {int} [pushStatus] 是否展示
     * @apiParam {int} [pushSort] 是否展示（一级越小越靠左，二级越小越靠上）
     * @apiParam {int} [showHome] 是否展示内容到首页，默认0不展示， 1展示
     * @apiParam {int} [showApp] 是否展示内容到APP，默认0不展示， 1展示
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:update")
    @RequiresPermissionsDesc(menu={"栏目管理" , "栏目分类"}, button="编辑")
    @PostMapping("/update")
    public Object update(@RequestBody GuopuCategory category) {
        Object error = validate(category);
        if (error != null) {
            return error;
        }

        if (!categoryService.updateById(category)) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /admin/category/delete 1.5 栏目删除
     * @apiName category delete
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 栏目id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:delete")
    @RequiresPermissionsDesc(menu={"栏目管理" , "栏目分类"}, button="删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody GuopuCategory category) {
        Integer id = category.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        categoryService.removeById(id);
        return ResponseUtil.ok();
    }

    /*@RequiresPermissions("admin:category:list")
    @GetMapping("/l1")
    public Object catL1() {
        // 所有一级分类目录
        List<NearbyshopCategory> l1CatList = categoryService.queryL1();
        List<Map<String, Object>> data = new ArrayList<>(l1CatList.size());
        for (NearbyshopCategory category : l1CatList) {
            Map<String, Object> d = new HashMap<>(2);
            d.put("value", category.getId());
            d.put("label", category.getName());
            data.add(d);
        }
        return ResponseUtil.ok(data);
    }*/

/*    *//**
     * 推商品到首页/取消推荐
     *
     * @param nearbyshopCategory  id: 分类id。  pushStatus:1：首页  0：非首页
     * @return
     *//*
    @RequiresPermissions("admin:category:push")
    @RequiresPermissionsDesc(menu = {"商品管理" , "商品分类"}, button="推到首页")
    @PostMapping("/push")
    public Object push(@RequestBody NearbyshopCategory nearbyshopCategory) {
        return adminCategoryService.push(nearbyshopCategory);
    }*/


    /**
     * @api {Post} /admin/category/sortUp 1.6 栏目上移
     * @apiName category sortUp
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 栏目id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:sortUp")
    @RequiresPermissionsDesc(menu = {"栏目管理" , "栏目分类"}, button="上移")
    @PostMapping("/sortUp")
    public Object sortUp(@RequestBody GuopuCategory category) {
        return categoryService.sortUp(category);
    }

    /**
     * @api {Post} /admin/category/sortDown 1.7 栏目下移
     * @apiName category sortDown
     * @apiGroup category
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 栏目id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:category:sortDown")
    @RequiresPermissionsDesc(menu = {"栏目管理" , "栏目分类"}, button="下移")
    @PostMapping("/sortDown")
    public Object sortDown(@RequestBody GuopuCategory nearbyshopCategory) {
        return categoryService.sortDown(nearbyshopCategory);
    }
}
